/*------------------------------------------------------------------------------
* Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team
*
* Distributable under the terms of either the Apache License (Version 2.0) or
* the GNU Lesser General Public License, as specified in the COPYING file.
------------------------------------------------------------------------------*/
#include <iostream>
#include <stdio.h>

#include "CLucene/StdHeader.h"
#include "CLucene/_clucene-config.h"

#include "CLucene.h"
#include "CLucene/config/repl_tchar.h"
#include "CLucene/config/repl_wchar.h"
#include "CLucene/util/Misc.h"

using namespace std;
using namespace lucene::analysis;
using namespace lucene::index;
using namespace lucene::util;
using namespace lucene::queryParser;
using namespace lucene::document;
using namespace lucene::search;


void SearchFiles(const char* index){
	standard::StandardAnalyzer analyzer;	// 提前准备一个标准的分词器
    char line[80];
    TCHAR tline[80];
    TCHAR* buf;

    IndexReader* reader = IndexReader::open(index);
	while (true) {	// 循环接收来自终端标准输入的查询内容（查询串不超过79字节）
        printf("Enter query string: ");
        char* tmp = fgets(line,80,stdin);
        if ( tmp == NULL ) continue;
        line[strlen(line)-1]=0;

		IndexReader* newreader = reader->reopen();	// 重新打开读取索引的对象，防止之前的对象已经断开
        if ( newreader != reader ){
            _CLLDELETE(reader);
            reader = newreader;
        }
		IndexSearcher s(reader);	// 通过搜索的方式使用读取索引的对象

		if ( strlen(line) == 0 )	// 如果不输入要查询的内容，就退出循环
            break;
		STRCPY_AtoT(tline,line,80);	// 转换为宽字符
		Query* q = QueryParser::parse(tline,_T("contents"),&analyzer);	// 将待查询的串通过分词转换为查询对象（查contents这个字段）

        buf = q->toString(_T("contents"));
        _tprintf(_T("Searching for: %s\n\n"), buf);
        _CLDELETE_LCARRAY(buf);

        uint64_t str = Misc::currentTimeMillis();
		Hits* h = s.search(q);	// 执行关键词的查询
        uint32_t srch = (int32_t)(Misc::currentTimeMillis() - str);
        str = Misc::currentTimeMillis();

		for ( size_t i=0;i<h->length();i++ ){	// 遍历每一个结果项
            Document* doc = &h->doc(i);
            //const TCHAR* buf = doc.get(_T("contents"));
			_tprintf(_T("%d. %s - %f\n"), i, doc->get(_T("path")), h->score(i));	// 打印结果所在的path字段值和结果的分值
        }

        printf("\n\nSearch took: %d ms.\n", srch);
        printf("Screen dump took: %d ms.\n\n", (int32_t)(Misc::currentTimeMillis() - str));

        _CLLDELETE(h);
        _CLLDELETE(q);

        s.close();
    }
    reader->close();
    _CLLDELETE(reader);
}

